package com.topsec.tss.hdfs.api;

import java.io.InputStream;
import java.util.Properties;


/**
 * @author yangpengfei
 */
public class ApiFactory {

    private static ApiFactory instance;
    private String serverUrl;
    Properties conf = new Properties();

    private ApiFactory(){
        loadConfiguration("api.properties");
    }

    public  synchronized static ApiFactory getInstance() {
        if(instance == null){
            instance = new ApiFactory();
        }
        return instance;
    }

    /**
     * 加载指定配置文件内容.
     */
    private void loadConfiguration(String configurationName){
        Properties config = new Properties();

        InputStream configInputStream = null;
        try {
            configInputStream = this.getClass().getClassLoader().getResourceAsStream(configurationName);
            if (configInputStream == null) {
                throw new RuntimeException("Can't find the default configuration file:" + configurationName);
            }
            config.load(configInputStream);
            setConf(config);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (configInputStream != null) {
                try {
                    configInputStream.close();
                } catch (Exception e) {

                }
            }
        }
    }

    public EventApi getEventApi() {
        String implClassName = (String)getConf().get(EventApi.class.getName());
        return buildApi(implClassName);
    }

    private EventApi buildApi(String className) {
        try {
            if (className == null || className.trim().length() == 0) {
                throw new Exception("implement class type is null, "+className);
            }

            Class<EventApi> apiClass = (Class<EventApi>) Class.forName(className);
            EventApi api = apiClass.newInstance();
            return api;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getServerUrl() {
        return serverUrl;
    }

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public Properties getConf() {
        return conf;
    }

    public void setConf(Properties conf) {
        this.conf = conf;
    }
}
